package com.pwt.service;

import com.pwt.common.CustomException;
import com.pwt.entity.*;
import com.pwt.model.what.*;
import com.pwt.repository.*;
import com.pwt.utils.DoubleUtils;
import com.pwt.utils.MathUtil;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class WatchChartsService {

    @Autowired
    WERTEVARRepository wertevarRepository;

    @Autowired
    ZzWatchChartsRepository zzWatchChartsRepository;

    @Autowired
    PRUEFERRepository prueferRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    WhatLineRepository whatLineRepository;

    @Autowired
    WhatLineService whatLineService;

    @Autowired
    HierarchyRepository hierarchyRepository;

    @Autowired
    AbilityLineService abilityLineService;

    @Autowired
    CrustalLusService crustalLusService;

    @Autowired
    MASCHINERepository maschineRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    WhatResultService whatResultService;

    @Autowired
    StatisticsPercentRepository statisticsPercentRepository;

    @Autowired
    AcceptanceLimitRepository acceptanceLimitRepository;

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    public List<WhatChatsModel> charts(Date start, Date end, String cfgId, List<Integer> machineIds) throws CustomException {
        //返回对象
        List<WhatChatsModel> list = new ArrayList<>();
        //已选统计类型
        List<ProductStatistics> selectedStatistics = whatResultService.getProductStatisticsList(cfgId);
        //百分数计算
        List<StatisticsPercent> statisticsPercentsList = statisticsPercentRepository.findAll();

        //根据机器id分组
        Map<Integer, List<ZzWatchCharts>> groupZz = new HashMap<>();
        //查询所有的实时零件编号  k1000
        List<ZzWatchCharts> zzWatchCharts = this.zzWatchChartsRepository.queryZzWatchChartsBykAndK0010AndkAndK0004(machineIds, start, end);
        zzWatchCharts.stream().forEach(zzWatchCharts1 -> {
            machineIds.stream().forEach(maschineid -> {
                if (maschineid.equals(zzWatchCharts1.getK0010())) {
                    if (groupZz.get(maschineid) == null) groupZz.put(maschineid, new ArrayList<>());
                    else groupZz.get(maschineid).add(zzWatchCharts1);
                }
            });
        });
        groupZz.keySet().forEach(id -> {
            WhatChatsModel whatChatsModel = new WhatChatsModel();
            whatChatsModel.setMachineId(id);
            whatChatsModel.setZzWatchChartsList(groupZz.get(id));
            whatChatsModel.setWhatStaticModelList(computeStatistics(groupZz.get(id), selectedStatistics, statisticsPercentsList));
            list.add(whatChatsModel);
        });
        return list;
    }

    public List<WhatChatsModel> queryData(Date start, Date end, String cfgId, List<Integer> machineIds) throws CustomException {
        //返回对象
        List<WhatChatsModel> list = new ArrayList<>();
        //根据机器id分组
        Map<Integer, List<ZzWatchCharts>> groupZz = new HashMap<>();
        //查询所有的实时零件编号  k0010
        List<ZzWatchCharts> zzWatchCharts = this.zzWatchChartsRepository.queryZzWatchChartsBykAndK0010AndkAndK0004(machineIds, start, end);
        zzWatchCharts.stream().forEach(zzWatchCharts1 -> {
            machineIds.stream().forEach(maschineid -> {
                if (maschineid.equals(zzWatchCharts1.getK0010())) {
                    if (groupZz.get(maschineid) == null) groupZz.put(maschineid, new ArrayList<>());
                    else groupZz.get(maschineid).add(zzWatchCharts1);
                }
            });
        });

        if (groupZz != null && groupZz.size() > 0) {
            groupZz.keySet().stream().forEach(id -> {
                WhatChatsModel whatChatsModel = new WhatChatsModel();
                whatChatsModel.setMachineId(id);
                whatChatsModel.setZzWatchChartsList(groupZz.get(id));
                list.add(whatChatsModel);
            });
        }
        return list;
    }

    //查询监控统计数据
    public List<WhatChatsModel> queryIndicatorValues(String cfgId, List<Integer> machineIds, Date start, Date end) {
        //已选统计类型
        List<ProductStatistics> selectedStatistics = whatResultService.getProductStatisticsList(cfgId);
        //百分数计算
        List<StatisticsPercent> statisticsPercentsList = statisticsPercentRepository.findAll();

        //根据机器id分组
        Map<Integer, List<ZzWatchCharts>> groupZz = new HashMap<>();
        //查询所有的实时零件编号  k1000
        List<ZzWatchCharts> zzWatchCharts = this.zzWatchChartsRepository.queryZzWatchChartsBykAndK0010AndkAndK0004(machineIds, start, end);
        zzWatchCharts.stream().forEach(zzWatchCharts1 -> {
            machineIds.stream().forEach(maschineid -> {
                if (maschineid.equals(zzWatchCharts1.getK0010())) {
                    if (groupZz.get(maschineid) == null) groupZz.put(maschineid, new ArrayList<>());
                    else groupZz.get(maschineid).add(zzWatchCharts1);
                }
            });
        });
        List<WhatChatsModel> list = new ArrayList<>();
        groupZz.keySet().forEach(id -> {
            WhatChatsModel whatChatsModel = new WhatChatsModel();
            List<WhatStaticModel> whatStaticModelList = computeStatistics(groupZz.get(id), selectedStatistics, statisticsPercentsList);
            whatChatsModel.setMachineId(id);
            whatChatsModel.setWhatStaticModelList(whatStaticModelList);
            list.add(whatChatsModel);
        });

        return list;
    }

    //查询
    public WhatChatsHeader queryStatisticsAttribute(String cfgId, String whatLineId) {
        WhatChatsHeader whatChatsModel = new WhatChatsHeader();
        //已选统计类型
        List<ProductStatistics> selectedStatistics = whatResultService.getProductStatisticsList(cfgId);
        //已选属性测试
        List<ProductAttribute> selectedAttribute = whatResultService.getProductAttributeList(cfgId);
        whatChatsModel.setStatistics(selectedStatistics);
        whatChatsModel.setAttributes(selectedAttribute);

        List<Hierarchy> list = new ArrayList<>();
        if (whatLineId == null) {
            list = this.whatLineService.queryAllHierarchy();
        } else {
            list = this.whatLineService.queryHierarchyByWhatLineId(whatLineId);
        }

        List<WhatHierarchyModel> treeList = new ArrayList<>();
        treeList = queryHierarchy(list, treeList);
        //机器id集合
        List<Integer> machineIds = new ArrayList<>();
        for (WhatHierarchyModel hierarchyModel : treeList) {
            if (hierarchyModel != null && hierarchyModel.getMachineId() != null) {
                machineIds.add(hierarchyModel.getMachineId());
            }

        }
        whatChatsModel.setHierarchyList(treeList);
        whatChatsModel.setMachineIds(machineIds);
        return whatChatsModel;
    }

    //树形结构转换成集合
    public List<WhatHierarchyModel> queryHierarchy(List<Hierarchy> list, List<WhatHierarchyModel> treeList) {
        for (Hierarchy h : list) {
            WhatHierarchyModel hierarchyModel = new WhatHierarchyModel();
            hierarchyModel.setId(h.getId());
            hierarchyModel.setName(h.getName());
            hierarchyModel.setMachineId(h.getNumber());
            treeList.add(hierarchyModel);
            if (h.getChildren() != null && h.getChildren().size() > 0) {
                queryHierarchy(h.getChildren(), treeList);
            }
        }
        return treeList;
    }

    //计算统计
    public List<WhatStaticModel> computeStatistics(List<ZzWatchCharts> groupZz, List<ProductStatistics> selectedStatistics, List<StatisticsPercent> statisticsPercentsList) {
        if (groupZz.size() > 0) {
            AtomicReference<Integer> ok = new AtomicReference<>(0);
            AtomicReference<Integer> SOMEOK = new AtomicReference<>(0);
            AtomicReference<Integer> NOK = new AtomicReference<>(0);
            AtomicReference<Integer> BAD = new AtomicReference<>(0);
            AtomicReference<Integer> total = new AtomicReference<>(0);
            groupZz.stream().forEach(zzWatchCharts1 -> {
                if (zzWatchCharts1 != null && StringUtils.isNotBlank(zzWatchCharts1.getRIGHTSTATUS())) {
                    String state = zzWatchCharts1.getRIGHTSTATUS();
                    if (state.equals("OK")) ok.getAndSet(ok.get() + 1);
                    if (state.equals("SOMEOK")) ok.getAndSet(SOMEOK.get() + 1);
                    if (state.equals("NOK")) ok.getAndSet(NOK.get() + 1);
                    if (state.equals("BAD")) BAD.getAndSet(BAD.get() + 1);
                }
            });
            total.getAndSet(ok.get() + SOMEOK.get() + NOK.get() + BAD.get());
            //统计集合
            List<WhatStaticModel> whatStaticModelList = new ArrayList<>();
            //统计类型，1-产品名，2-合格，3-不合格，4-总数，5质量，6-报废
            if (selectedStatistics != null && selectedStatistics.size() > 0)
                selectedStatistics.stream().forEach(statistics -> {
                    WhatStaticModel whatStaticModel = new WhatStaticModel();
                    if (statistics.getType() == 1) {
                        whatStaticModel.setValue(groupZz.get(0).getK1002());
                    }
                    if (statistics.getType() == 2) {
                        whatStaticModel.setValue(ok.get() + SOMEOK.get());
                    }
                    if (statistics.getType() == 3) {
                        whatStaticModel.setValue(NOK.get() + BAD.get());
                    }
                    if (statistics.getType() == 4) {
                        whatStaticModel.setValue(total);
                    }
                    //质量
                    if (statistics.getType() == 5) {
                        Double quality = MathUtil.divDouble(ok.get() * 1.00, total.get() * 1.00);
                        quality = DoubleUtils.retainPercent2(quality);
                        List<StatisticsPercent> statisticsPercents = statisticsPercentsList.stream().filter(statisticsPercent -> statisticsPercent.equals(statistics.getId())).collect(Collectors.toList());
                        whatStaticModel.setValue(quality);
                        if (statisticsPercents == null || statisticsPercents.size() < 1) {
                            whatStaticModel.setColor(statistics.getColor());
                        } else {
                            for (StatisticsPercent percent : statisticsPercents) {
                                if (quality >= percent.getStartPercent() && quality <= percent.getEndPercent()) {
                                    whatStaticModel.setColor(percent.getColor());
                                }
                            }
                        }
                    }

                    if (statistics.getType() == 6) {
                        whatStaticModel.setValue(BAD);
                    }

                    whatStaticModel.setId(statistics.getId());
                    whatStaticModel.setColor(statistics.getColor());
                    whatStaticModel.setType(statistics.getType());
                    whatStaticModelList.add(whatStaticModel);
                });


            return whatStaticModelList;
        }
        return null;
    }
}
